package com.example.demo.contorller;

import com.example.demo.bean.Department;
import com.example.demo.common.ResponseCode;
import com.example.demo.common.ServerResponse;
import com.example.demo.service.DepartmentService;
import lombok.AllArgsConstructor;
import org.springframework.data.jpa.repository.support.QuerydslJpaRepository;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @author ouyangzhixiang
 * @date 2018/6/22
 */
@RequestMapping("/department/")
@RestController
@AllArgsConstructor
public class DepartmentController {

    private final DepartmentService departmentService;

    /**
     * 查找部门信息列表
     *
     * @param parentId
     * @return
     */
    @GetMapping("list/{parentId}")
    public ServerResponse<List<Department>> list(@PathVariable("parentId") Integer parentId) {
        return departmentService.selectId(parentId);
    }

    /**
     * 部门信息单个查找
     *
     * @param id 接受主键传入Id
     * @return
     */
    @GetMapping("get_find_one/{id}")
    public ServerResponse findOne(@PathVariable("departmentId") Integer id) {
        return departmentService.getFindOne(id);
    }

    /**
     * 添加部门
     *
     * @param department 对象传入
     * @return
     */
    @PostMapping("add_department")
    public ServerResponse<Department> addDpartment(@Valid Department department, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        return departmentService.addDepartment(department);
    }

    /**
     * 删除部门
     *
     * @param id 主键传入Id进行删除
     */
    @DeleteMapping("delete_department/{departmentId}")
    public void deleteDepartment(@PathVariable("departmentId") Integer id) {
        departmentService.deleteDepartment(id);
    }

    /**
     * 更新部门数据
     *
     * @param department 通过主键Id更新
     * @return
     */
    @PutMapping("department_update")
    public ServerResponse<Department> departmentUpdate(Department department) {
        ServerResponse<Department> departmentServerResponse = departmentService.departmentUpdate(department);
        return departmentServerResponse;
    }
}
